package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.common.Result;
import com.shopping_back.mapper.*;
import com.shopping_back.pojo.entity.*;
import com.shopping_back.service.IFullReductionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class FullReductionServiceImpl implements IFullReductionService {

    private final PromotionActivityMapper promotionActivityMapper;
    private final FullReductionItemMapper fullReductionItemMapper;
    private final SkuMapper skuMapper;
    private final SpuMapper spuMapper;
    private final OrderMainMapper orderMainMapper;
    private final OrderItemMapper orderItemMapper;

    @Override
    public Result getFullReductionActivity(Long activityId) {
        PromotionActivity activity = promotionActivityMapper.selectById(activityId);
        if (activity == null || !activity.getType().equals(3)) {
            return Result.error("满减活动不存在");
        }
        return Result.success(activity);
    }

    public Result getFullReductionItems(Long activityId, Integer page, Integer size) {
        Page<FullReductionItem> itemPage = new Page<>(page, size);
        LambdaQueryWrapper<FullReductionItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FullReductionItem::getActivityId, activityId);
        fullReductionItemMapper.selectPage(itemPage, queryWrapper);
        for (FullReductionItem item : itemPage.getRecords()) {
            Sku sku = skuMapper.selectById(item.getSkuId());
            if (sku != null) {
                item.setSkuPrice(sku.getPrice()); // 设置商品原始价格
                Spu spu = spuMapper.selectById(sku.getSpuId());
                if (spu != null) {
                    item.setSkuName(spu.getTitle());
                    item.setSpuMainImage(spu.getMainImage());
                }
                item.setSkuImage(sku.getSkuImage());
            } else {
                item.setSkuName("未知商品");
                item.setSkuPrice(BigDecimal.ZERO);
                item.setSpuMainImage("");
                item.setSkuImage("");
            }
        }
        return Result.success(itemPage);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result placeFullReductionOrder(Long userId, Long activityId, Map<Long, Integer> skuQuantities) {
        // 检查活动状态
        PromotionActivity activity = promotionActivityMapper.selectById(activityId);
        if (activity == null || !activity.getType().equals(3) || activity.getStatus() != 1 ||
                LocalDateTime.now().isBefore(activity.getStartTime()) || LocalDateTime.now().isAfter(activity.getEndTime())) {
            return Result.error("满减活动不可用或已结束");
        }

        // 检查商品
        List<FullReductionItem> fullReductionItems = fullReductionItemMapper.selectList(new LambdaQueryWrapper<FullReductionItem>()
                .eq(FullReductionItem::getActivityId, activityId));
        if (fullReductionItems.isEmpty()) {
            return Result.error("满减商品不存在");
        }

        // 验证skuQuantities
        if (skuQuantities == null || skuQuantities.isEmpty()) {
            return Result.error("请至少选择一种商品");
        }
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Map.Entry<Long, Integer> entry : skuQuantities.entrySet()) {
            Long skuId = entry.getKey();
            Integer quantity = entry.getValue();
            if (quantity <= 0) {
                return Result.error("购买数量需大于0");
            }
            FullReductionItem item = fullReductionItems.stream()
                    .filter(i -> i.getSkuId().equals(skuId))
                    .findFirst()
                    .orElse(null);
            if (item == null) {
                return Result.error("商品不在满减活动中: " + skuId);
            }
            Sku sku = skuMapper.selectById(skuId);
            if (sku == null) {
                return Result.error("商品不存在: " + skuId);
            }
            totalAmount = totalAmount.add(sku.getPrice().multiply(new BigDecimal(quantity)));
        }

        // 满减逻辑
        FullReductionItem rule = fullReductionItems.get(0); // 假设活动内规则一致
        BigDecimal payAmount = totalAmount;
        BigDecimal promotionAmount = BigDecimal.ZERO;

// 添加完整的null检查
        if (totalAmount != null && rule != null && rule.getThreshold() != null) {
            if (totalAmount.compareTo(rule.getThreshold()) >= 0) {
                BigDecimal discount = rule.getDiscount();
                if (discount != null) {
                    payAmount = totalAmount.subtract(discount);
                    promotionAmount = discount;
                }
            }
        } else {
            // 处理异常情况
            if (totalAmount == null) {
                throw new RuntimeException("订单总金额计算错误");
            }
            if (rule == null || rule.getThreshold() == null) {
                throw new RuntimeException("满减规则配置错误");
            }
        }

        // 创建订单
        OrderMain order = createOrder(userId, activityId, skuQuantities, totalAmount, payAmount, promotionAmount, rule);
        return Result.success(order, "下单成功");
    }

    @Transactional(rollbackFor = Exception.class)
    protected OrderMain createOrder(Long userId, Long activityId, Map<Long, Integer> skuQuantities, BigDecimal totalAmount, BigDecimal payAmount, BigDecimal promotionAmount, FullReductionItem rule) {
        OrderMain order = new OrderMain();
        order.setOrderSn(UUID.randomUUID().toString().replace("-", ""));
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setPayAmount(payAmount);
        order.setPromotionAmount(promotionAmount);
        order.setStatus(0);
        order.setMerchantId(0L); // 假设统一商家
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderMainMapper.insert(order);

        for (Map.Entry<Long, Integer> entry : skuQuantities.entrySet()) {
            Sku sku = skuMapper.selectById(entry.getKey());
            Spu spu = spuMapper.selectById(sku.getSpuId());
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setSkuId(entry.getKey());
            orderItem.setSkuName(spu.getTitle());
            orderItem.setSkuPrice(sku.getPrice());
            orderItem.setQuantity(entry.getValue());
            orderItem.setActivityId(activityId);
            orderItem.setSubTotal(sku.getPrice().multiply(new BigDecimal(entry.getValue())));
            orderItem.setCreateTime(LocalDateTime.now());
            orderItemMapper.insert(orderItem);
        }

        return order;
    }
}
